package com.wf.course.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.google.gson.Gson;
import com.utils.dateUtil.DateUtil;
import com.utils.page.PageBean;
import com.wf.course.dao.ICoinLogMapper;
import com.wf.course.dao.ICourseCategoryMapper;
import com.wf.course.dao.IGoodsOrderRelationMapper;
import com.wf.course.model.goods.GoodsOrderRelation;
import com.wf.course.service.IGoodsOrderRelationService;

@Service
@Transactional(rollbackFor = Exception.class)
public class IGoodsOrderRelationServiceImpl implements IGoodsOrderRelationService {

    @Autowired
    private IGoodsOrderRelationMapper mapper;
    @Autowired
    private ICoinLogMapper clMapper;
    @Autowired
    private ICourseCategoryMapper clMappers;

    @Override
    public void indexInfo(PageBean<GoodsOrderRelation> pageBean) {
        // TODO Auto-generated method stub
        List<GoodsOrderRelation> lists = this.mapper.queryList(pageBean);
        for (GoodsOrderRelation gors : lists) {
            String speakerName = "";
            int sort = gors.getGoodsSort();
            if (sort == 3) {
                List<GoodsOrderRelation> listName = this.mapper.getOrderCodes(gors.getOrderCode());


                if (listName != null && listName.size() > 0) {

                    for (int i = 0; i < listName.size(); i++) {
                        if (listName.get(i) != null) {
                            speakerName += listName.get(i).getSpeakerName() + "\n";
                        }
                    }
                }
                gors.setSpeakerName(speakerName);

            } else {

                gors.setSpeakerName(gors.getSpeakerName());
            }
            //赋值原铜钱
            if (gors.getVersion() == null || "".equals(gors.getVersion())) {
                gors.setOldCopperCash(gors.getCopperCash());
            } else if (gors.getVersion().equals("2.0")) {
                gors.setOldCopperCash(gors.getCopperCash());
            } else if (gors.getVersion().equals("3.0")) {
                gors.setOldCopperCash(gors.getOldCopperCash());
            }
            //赋值误差值
            if (gors.getVersion() == null || "".equals(gors.getVersion())) {
                String errorvalues = gors.getErrorvalues();
                if ("".equals(errorvalues) || errorvalues == null) {
                    gors.setErrorvalue("0.00");
                } else {
                    gors.setErrorvalue(gors.getErrorvalues());
                }
            } else if (gors.getVersion().equals("2.0")) {
                String errorvalues = gors.getErrorvalues();
                if ("".equals(errorvalues) || errorvalues == null) {
                    gors.setErrorvalue("0.00");
                } else {
                    gors.setErrorvalue(gors.getErrorvalues());
                }
            } else if (gors.getVersion().equals("3.0")) {
                gors.setErrorvalue(gors.getErrorvalue());
            }
        }
        pageBean.setResults(lists);
        pageBean.setTotalCount(this.mapper.getTotalCount(pageBean).intValue());
    }

    @Override
    public void saveGoodsOrderRelationOrUpdate(GoodsOrderRelation goodsOrderRelation) {
        // TODO Auto-generated method stub
        if (goodsOrderRelation.getId() == null) {
            this.mapper.saveGoodsOrderRelation(goodsOrderRelation);
        } else {
            if (goodsOrderRelation.getGoodsSort() == 1 && goodsOrderRelation.getCourseId() != null) {
                goodsOrderRelation.setGoodsId(goodsOrderRelation.getCourseId());
            } else if (goodsOrderRelation.getGoodsSort() == 2 && goodsOrderRelation.getChapterId() != null) {
                goodsOrderRelation.setGoodsId(goodsOrderRelation.getChapterId());
            } else if (goodsOrderRelation.getGoodsSort() == 3 && goodsOrderRelation.getCardId() != null) {
                goodsOrderRelation.setGoodsId(goodsOrderRelation.getCardId());
            }
            this.mapper.updateGoodsOrderRelation(goodsOrderRelation);
        }

    }

    @Override
    public GoodsOrderRelation queryGoodsOrderRelationById(Integer id) {
        // TODO Auto-generated method stub
        return this.mapper.queryGoodsOrderRelationById(id);
    }

    @Override
    public void deleteById(Integer id) {
        // TODO Auto-generated method stub
        this.mapper.deleteById(id);
    }


    @Override
    public List<GoodsOrderRelation> queryOrderGoodsList(String orderCode) {
        // TODO Auto-generated method stub
        return this.mapper.queryOrderGoodsList(orderCode);
    }

    /**
     * 根据订单编号，查询订单详情
     *
     * @param orderCode
     * @return
     */
    @Override
    public List<GoodsOrderRelation> queryOrderGoodsListByOrderCode(@Param("orderCode") String orderCode) {
        // TODO
        return this.mapper.queryOrderGoodsListByOrderCode(orderCode);
    }

    @Override
    public List<GoodsOrderRelation> getCourseAmount(String userSource, String orderBeginTime, String orderEndTime) {
        // TODO Auto-generated method stub
        return this.mapper.getCourseAmount(userSource, orderBeginTime, orderEndTime);
    }

    @Override
    public List<GoodsOrderRelation> getGoodsAmount(String userSource, String orderBeginTime, String orderEndTime) {
        // TODO Auto-generated method stub
        return this.mapper.getGoodsAmount(userSource, orderBeginTime, orderEndTime);
    }

    @Override
    public void deleteByOrderCode(String OrderCode) {
        // TODO Auto-generated method stub
        this.mapper.deleteByOrderCode(OrderCode);
    }

    @Override
    public void getGoodsSale(PageBean<GoodsOrderRelation> pageBean) {
        // TODO Auto-generated method stub
        pageBean.setResults(this.mapper.getGoodsSale(pageBean));
        pageBean.setTotalCount(this.mapper.getGoodsSaleNum(pageBean).intValue());

        String userSource = "";
        String orderBeginTime = "";
        String orderEndTime = "";
        String speakerName = "";
        String ccname = "";
        Integer goodsSort = 0;

        List<GoodsOrderRelation> grls = pageBean.getResults();
        if (pageBean.getConMap() != null && pageBean.getConMap().size() > 0) {
            if (pageBean.getConMap().get("userSource") != null && !"".equals(pageBean.getConMap().get("userSource"))) {
                userSource = pageBean.getConMap().get("userSource").toString();
            }
            if (pageBean.getConMap().get("orderBeginTime") != null && !"".equals(pageBean.getConMap().get("orderBeginTime"))) {
                orderBeginTime = pageBean.getConMap().get("orderBeginTime").toString();
            }
            if (pageBean.getConMap().get("speakerName") != null && !"".equals(pageBean.getConMap().get("speakerName"))) {
                speakerName = pageBean.getConMap().get("speakerName").toString();
            }
            if (pageBean.getConMap().get("orderEndTime") != null && !"".equals(pageBean.getConMap().get("orderEndTime"))) {
                orderEndTime = pageBean.getConMap().get("orderEndTime").toString();
            }
            if (pageBean.getConMap().get("goodsSort") != null && !"".equals(pageBean.getConMap().get("goodsSort"))) {
                goodsSort = Integer.parseInt(pageBean.getConMap().get("goodsSort").toString());
            }
        }

        if (grls != null && grls.size() > 0) {
            for (GoodsOrderRelation gor : grls) {
                //商品编号
                Integer goodsId = gor.getGoodsId();
//				goodsSort = gor.getGoodsSort();
                List<GoodsOrderRelation> grs = this.mapper.getGoodsCount(goodsId, goodsSort, userSource, orderBeginTime, orderEndTime, speakerName);

                int sort = gor.getGoodsSort();
                //去查id=3vip 的老师名称
                if (sort == 3) {
                    List<GoodsOrderRelation> listName = this.mapper.getGoodsid(gor.getGoodsId());

                    String speakerNames = "";
                    String ccnames = "";
                    if (listName != null && listName.size() > 0) {

                        for (int i = 0; i < listName.size(); i++) {
                            if (listName.get(i) != null) {
                                speakerNames += listName.get(i).getSpeakerName() + "\n";
                            }
                        }
                    }
                    //去查id=3vip 二级分类
                    List<GoodsOrderRelation> listNames = this.mapper.getOrderCodesName(gor.getGoodsId());
                    if (listNames != null && listNames.size() > 0) {

                        for (int i = 0; i < listNames.size(); i++) {
                            if (listNames.get(i) != null) {
                                ccnames += listNames.get(i).getCcname() + "\n";
                            }
                        }
                    }
                    gor.setCcname(ccnames);
                    gor.setSpeakerName(speakerNames);

                } else {

                    gor.setSpeakerName(gor.getSpeakerName());
                    gor.setCcname(gor.getCcname());
                }


                //计算商品销量
                if (grs != null && grs.size() > 0) {
                    gor.setGoodsCount(grs.get(0).getGoodsCount());
                }


                /**
                 * 计算商品的销售额
                 * 1.根据商品编号和商品分类，查询订单列表
                 * 2.是否使用铜钱：否：判断订单总额？=商品价格；=，销售额取订单总额；！=：销售额取商品支付价格
                 * 3.使用铜钱：商品总额？=商品支付单价，=取订单总额;
                 *   !=;根据订单编号，查询商品订单关系表中的记录数量，比较价格，如果属于价格高的商品，销售额=单价-铜钱，属于价格低的，销售额取商品支付单价
                 */
                BigDecimal actualSales = new BigDecimal(0);
                //商品分类是1，2，3时
                if (gor.getGoodsSort() != 4) {

                    List<GoodsOrderRelation> gorders = this.mapper.getOrdersByGoodsIdAndType(goodsId, gor.getGoodsSort(), userSource, orderBeginTime, orderEndTime);
				/*if(gorders!=null && gorders.size()>0){
					for(GoodsOrderRelation g:gorders){
						//未使用铜钱
						if(g.getCopperCash()==null ){
							if(g.getOrderAmount()==g.getGoodsPrice()){
								actualSales=actualSales.add(g.getOrderAmount());
								
							}else{
								if(g.getGoodsPrice()!=null){
									actualSales=actualSales.add(g.getGoodsPrice());
								}
							}
						}else{
							if(new  BigDecimal(g.getGoodsAmount())==g.getGoodsPrice()){
								actualSales = actualSales.add(g.getOrderAmount());
							}else{
								BigDecimal bg = g.getGoodsPrice();
								BigDecimal initBg = new BigDecimal(0);//集合中的大值
								List<GoodsOrderRelation>  gors= this.mapper.queryOrderGoodsList(g.getOrderCode());
								if(gors!=null && gors.size()>0){
									for(GoodsOrderRelation grl:gors){
										  int s = bg.compareTo(grl.getGoodsPrice());
										  if(s==-1){//小于
											  initBg = grl.getGoodsPrice();
										  }else{
											  initBg = bg;
										  }
									}
									int rs2 = bg.compareTo(initBg);
									if(rs2==-1){
										actualSales = actualSales.add(g.getGoodsPrice());
									}else{
										CoinLog coinlg = clMapper.queryCoinLogByOrderCode(g.getOrderCode(), 2);
										if(coinlg!=null){
											BigDecimal bg3 = bg.subtract(new BigDecimal(coinlg.getCoinValue()));
											actualSales = actualSales.add(bg3);
										}
										
									}
									
								}
							}
						}
					}
				}
				gor.setSaleNum(actualSales.toString());*/
                }


            }
        }
    }

    /**
     * 1.查询条件设置
     * 2.根据查询条件，查销量
     */
    @Override
    public List<GoodsOrderRelation> exportGoodSales(PageBean<GoodsOrderRelation> pageBean) {
        // TODO Auto-generated method stub
        Long start = System.currentTimeMillis();

        String userSource = pageBean.getConMap().get("userSource") != null ?
                pageBean.getConMap().get("userSource").toString() : "";
        String orderBeginTime = pageBean.getConMap().get("orderBeginTime") != null ?
                pageBean.getConMap().get("orderBeginTime").toString() : "";
        String orderEndTime = pageBean.getConMap().get("orderEndTime") != null ?
                pageBean.getConMap().get("orderEndTime").toString() : "";
        String speakerName = pageBean.getConMap().get("speakerName") != null ?
                pageBean.getConMap().get("speakerName").toString() : "";

        List<GoodsOrderRelation> grls = this.mapper.exportGoodSales(pageBean);
        ExecutorService service = Executors.newCachedThreadPool();
        for (GoodsOrderRelation gor : grls) {
            service.execute(new Runnable() {
                @Override
                public void run() {
                    Integer goodsId = gor.getGoodsId();
                    Integer goodsSort = gor.getGoodsSort();

                    //查询每种商品的总销量
                    List<GoodsOrderRelation> grs = mapper.getGoodsCount(goodsId, goodsSort, userSource, orderBeginTime, orderEndTime, speakerName);
                    gor.setGoodsCount(grs.get(0).getGoodsCount());
                    //去查id=3vip 的老师名称
                    int sort = gor.getGoodsSort();
                    if (sort == 3) {
                        List<GoodsOrderRelation> listName = mapper.getGoodsid(gor.getGoodsId());

                        String speakerNames = "";
                        String ccnames = "";
                        if (listName != null && listName.size() > 0) {

                            for (int i = 0; i < listName.size(); i++) {
                                if (listName.get(i) != null) {
                                    speakerNames += listName.get(i).getSpeakerName() + "\n";
                                }
                            }
                        }
                        //去查id=3vip 二级分类
                        List<GoodsOrderRelation> listNames = mapper.getOrderCodesName(gor.getGoodsId());
                        if (listNames != null && listNames.size() > 0) {

                            for (int i = 0; i < listNames.size(); i++) {
                                if (listNames.get(i) != null) {
                                    ccnames += listNames.get(i).getCcname() + "\n";
                                }
                            }
                        }

                        gor.setCcname(ccnames);
                        gor.setSpeakerName(speakerNames);

                    } else {
                        //查询每种商品的二级分类
                        List<GoodsOrderRelation> grst = mapper.getGoodsCcname(goodsId, goodsSort, userSource, orderBeginTime, orderEndTime);

                        if (grst.get(0) != null) {
                            gor.setCcname(grst.get(0).getCcname());
                        }
                        //查询授课老师
                        List<GoodsOrderRelation> teacher = mapper.getSpeakerName(goodsId, goodsSort, userSource, orderBeginTime, orderEndTime);
                        gor.setSpeakerName(teacher.get(0).getSpeakerName());
                    }

                    List<GoodsOrderRelation> oldCopperCash = mapper.getCopperCome(goodsId, goodsSort, userSource, orderBeginTime, orderEndTime);
                    gor.setOldCopperCash(oldCopperCash.get(0).getOldCopperCash());
                    //查询新铜钱消耗
                    List<GoodsOrderRelation> newCopperCash = mapper.getCopperCome(goodsId, goodsSort, userSource, orderBeginTime, orderEndTime);
                    gor.setNewCopperCash(newCopperCash.get(0).getNewCopperCash());
			/*//查询实际支付
			List<GoodsOrderRelation> realIncome = this.mapper.getCopperCome(goodsId,goodsSort,userSource,orderBeginTime,orderEndTime);
			gor.setRealIncome(realIncome.get(0).getRealIncome());*/

                    //查询销售额
                    List<GoodsOrderRelation> saleNum = mapper.getCopperCome(goodsId, goodsSort, userSource, orderBeginTime, orderEndTime);
                    gor.setSaleNum(saleNum.get(0).getSaleNum());

                    //如果商品分类是4：查询商品的运费
                    GoodsOrderRelation gorl = mapper.getGoodsFreight(goodsSort, userSource, orderBeginTime, orderEndTime);
                    gor.setFreight(gorl.getFreight());

                    /**
                     * 计算商品的销售额
                     * 1.根据商品编号和商品分类，查询订单列表
                     * 2.是否使用铜钱：否：判断订单总额？商品价格，=，取订单总额；！=：取商品支付价格
                     * 3.使用铜钱：商品总额？=商品支付单价，=取订单总额;
                     * 4.!=;根据订单编号，查询商品订单关系表中的记录数量，比较价格，如果属于价格高的商品，取单价-铜钱，属于价格低的，取商品支付单价
                     */
		/*	BigDecimal actualSales = new  BigDecimal(0);
			//商品分类是1，2，3时
			if(gor.getGoodsSort()!=4){*/

                    //注释计算销售额
			/*List<GoodsOrderRelation> gorders  = this.mapper.getOrdersByGoodsIdAndType(goodsId,gor.getGoodsSort(),userSource,orderBeginTime,orderEndTime);
			if(gorders!=null && gorders.size()>0){
				for(GoodsOrderRelation g:gorders){
					//未使用铜钱
					if(g.getCopperCash()==null ){
						if(g.getOrderAmount()==g.getGoodsPrice()){
							actualSales=actualSales.add(g.getOrderAmount());
							
						}else{
							if(g.getGoodsPrice()!=null){
								actualSales=actualSales.add(g.getGoodsPrice());
							}
						}
					}else{
						if(new  BigDecimal(g.getGoodsAmount())==g.getGoodsPrice()){
							actualSales = actualSales.add(g.getOrderAmount());
						}else{
							BigDecimal bg = g.getGoodsPrice();
							BigDecimal initBg = new BigDecimal(0);//集合中的大值
							List<GoodsOrderRelation>  gors= this.mapper.queryOrderGoodsList(g.getOrderCode());
							if(gors!=null && gors.size()>0){
								for(GoodsOrderRelation grl:gors){
									  int s = bg.compareTo(grl.getGoodsPrice());
									  if(s==-1){//小于
										  initBg = grl.getGoodsPrice();
									  }else{
										  initBg = bg;
									  }
								}
								int rs2 = bg.compareTo(initBg);
								if(rs2==-1){
									actualSales = actualSales.add(g.getGoodsPrice());
								}else{
									CoinLog coinlg = clMapper.queryCoinLogByOrderCode(g.getOrderCode(), 2);
									if(coinlg!=null){
										BigDecimal bg3 = bg.subtract(new BigDecimal(coinlg.getCoinValue()));
										actualSales = actualSales.add(bg3);
									}
									
								}
								
							}
						}
					}
				}
			}*/
                    /*gor.setSaleNum(actualSales.toString());*/
                    /*} */

                }

            });
        }
        service.shutdown();
        while (true) {
            if (service.isTerminated()) {
                break;
            }
        }
        System.err.println(System.currentTimeMillis() - start);
        return grls;
    }

    @Override
    public void updateBackFlag(Integer id) {
        // TODO Auto-generated method stub
        this.mapper.updateBackFlag(id);
    }

    /**
     * 商品销售统计
     *
     * @param goodsSort
     * @return
     */
    @Override
    public String goodsSalesStatistics() {
        List<String> courseGoods = mapper.goodsSalesStatistics(1);
        List<String> chapterGoods = mapper.goodsSalesStatistics(2);
        List<String> vipcardGoods = mapper.goodsSalesStatistics(3);

        List<String> goodsTimes = mapper.goodsSalesStatisticsTimes();


        Map<String, Object> data = new HashMap<>();
        data.put("courseGoods", courseGoods);
        data.put("chapterGoods", chapterGoods);
        data.put("vipcardGoods", vipcardGoods);
        data.put("goodsTimes", goodsTimes);

        String result = new Gson().toJson(data);
        return result;
    }

    /**
     * 商品分类销售查询
     *
     * @param goodsSort
     * @param id
     * @return
     */
    @Override
    public String goodsCategoriesSales(Integer goodsSort, Integer id) {
        List<String> list = mapper.goodsCategoriesSales(goodsSort, id);
        List<String> goodsTimes = mapper.goodsSalesStatisticsTimes();

        Map<String, Object> map = new HashMap<>();
        map.put("list", list);
        map.put("goodsTimes", goodsTimes);

        String result = new Gson().toJson(map);

        return result;
    }

    @Override
    public String goodsCategoriesSalesByTimes(Integer goodsSort, Integer id, String orderPayTime) {
        // TODO Auto-generated method stub
        String[] timeString = {"00", "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23"};
        List<String> timeArray = Arrays.asList(timeString);

        String[] resultString = {"0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0", "0"};
        List<String> resultArray = Arrays.asList(resultString);

        ArrayList<GoodsOrderRelation> arrayList = this.mapper.goodsCategoriesSalesByTimes(goodsSort, id, orderPayTime);
        if (arrayList.size() > 0) {
            for (int i = 0, length = arrayList.size(); i < length; i++) {
                int index = timeArray.indexOf(arrayList.get(i).getOrderPayTime());
                if (index > -1) {
                    resultArray.set(index, arrayList.get(i).getSaleCounts().toString());
                }
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("timeString", timeString);
        map.put("resultString", resultString);
        return new Gson().toJson(map);
    }

    @Override
    public String goodsCategoriesSalesByDay(Integer goodsSort, Integer id, String orderPayTime) {
        // TODO Auto-generated method stub
        List<String> dayList = new ArrayList<>();
        dayList.add(DateUtil.getStringtoString(DateUtil.getDate(orderPayTime, -3), 2));
        dayList.add(DateUtil.getStringtoString(DateUtil.getDate(orderPayTime, -2), 2));
        dayList.add(DateUtil.getStringtoString(DateUtil.getDate(orderPayTime, -1), 2));
        dayList.add(DateUtil.getStringtoString(orderPayTime, 2));
        dayList.add(DateUtil.getStringtoString(DateUtil.getDate(orderPayTime, 1), 2));
        dayList.add(DateUtil.getStringtoString(DateUtil.getDate(orderPayTime, 2), 2));
        dayList.add(DateUtil.getStringtoString(DateUtil.getDate(orderPayTime, 3), 2));

        List<String> resultList = new ArrayList<>();
        resultList.add("0");
        resultList.add("0");
        resultList.add("0");
        resultList.add("0");
        resultList.add("0");
        resultList.add("0");
        resultList.add("0");

        ArrayList<GoodsOrderRelation> arrayList = this.mapper.goodsCategoriesSalesByDay(goodsSort, id, orderPayTime);
        if (arrayList.size() > 0) {
            for (int i = 0, length = arrayList.size(); i < length; i++) {

                int index = dayList.indexOf(arrayList.get(i).getOrderPayTime());
                if (index > -1) {
                    resultList.set(index, arrayList.get(i).getSaleCounts().toString());
                }
            }
        }
        Map<String, Object> map = new HashMap<>();
        map.put("dayList", dayList);
        map.put("resultList", resultList);
        return new Gson().toJson(map);
    }

    public List<GoodsOrderRelation> newExportGoodSales(Integer goodsSort, String userSource, String  orderBeginTime, String orderEndTime, String speakerName) {
        return mapper.newExportGoodSales(goodsSort, userSource, orderBeginTime, orderEndTime, speakerName);
    }

    @Override
    public void newGetGoodsSale(PageBean<GoodsOrderRelation> pageBean) {
        pageBean.setResults(mapper.newGetGoodsSale(pageBean));
        pageBean.setTotalCount(mapper.newGetGoodsSaleNum(pageBean));
    }

    @Override
    public List<GoodsOrderRelation> exportPurchaseAmountExcel(String beginTime, String endTime) {
        return mapper.exportPurchaseAmountExcel(beginTime, endTime);
    }

    @Override
    public void purchaseAmountList(PageBean<GoodsOrderRelation> pageBean) {
        pageBean.setResults(mapper.purchaseAmountList(pageBean));
        pageBean.setTotalCount(mapper.purchaseAmountCount(pageBean));
    }
}
